package com.splatform.rest;

import com.splatform.utils.ZipUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

/**
 * Created by sunfeihu on 2017/5/15.
 */
@RestController
public class HomeRestController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @PostMapping(value = "/login")
    public String login(String usern, String pwd, HttpServletRequest request) {
        if (usern.equals("admin") && pwd.equals("admin123!@#")) {
            request.getSession().setAttribute("login", true);
            return "ok";
        }
        return "fail";
    }

    @PostMapping(value = "/activity/add")
    public String add(String name, HttpServletRequest request) {
        Boolean isLogin = (Boolean) request.getSession().getAttribute("login");
        if (!isLogin) {
            return "nologin";
        }
        jdbcTemplate.update(" insert into activity (name) values (?) ", new Object[]{
                name
        });
        return "ok";
    }

    @PostMapping(value = "/activity/change/{aid}")
    public String change(@PathVariable Long aid, HttpServletRequest request) {
        Boolean isLogin = (Boolean) request.getSession().getAttribute("login");
        if (!isLogin) {
            return "nologin";
        }
        jdbcTemplate.update(" update activity set now_code = now_code + 1 where id = ? ", new Object[]{aid});
        return "ok";
    }

    @PostMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Boolean isLogin = (Boolean) request.getSession().getAttribute("login");
        if (!isLogin) {
            return "nologin";
        }
        String realPath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        realPath = realPath + File.separator + "static";
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String aid = request.getParameter("aid");
        String ext = file.getOriginalFilename();
        ext = ext.substring(ext.lastIndexOf("."));
        String fname = File.separator + UUID.randomUUID().toString().replaceAll("-", "");
        String myfolder = folder.getAbsolutePath() + fname;
        String name = myfolder + ext;
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                File f = new File(name);
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(f));
                stream.write(bytes);
                stream.close();
                //上传完成以后，进行解压，解压后把图片插入数据库
                ZipUtil.unZip(f.getAbsolutePath());
                File myfolderFile = new File(myfolder);
                File[] farr = myfolderFile.listFiles();
                jdbcTemplate.update(" delete from group_imgs where activity_id = ? ", new Object[]{
                        aid
                });
                String sql = " insert into group_imgs (activity_id,name,sort,scan_counts,path) values (?,?,?,?,?) ";
                for (int i = 0; i < farr.length; i++) {
                    jdbcTemplate.update(sql, new Object[]{
                            aid, FilenameUtils.getBaseName(farr[i].getName()), i, 0, fname + "/" + farr[i].getName()
                    });
                }
                return "ok";
            } catch (Exception e) {
                e.printStackTrace();
                return "fail";
            }
        } else {
            return "fail";
        }
    }

}